import http from '@/utils/request'
import { setTokenInfo } from '@/utils/storage'
import { AppDispatch } from '..'
import { Profile, UserAction } from '../reducer/user'

export const sendCode = (mobile: string) => async (dispatch: AppDispatch) => {
  const res = await http.get(`/v1_0/sms/codes/${mobile}`)
  console.log(res)
}

export const Authorizations =
  ({ mobile, code }: { mobile: string; code: string }) =>
  async (dispatch: AppDispatch) => {
    const res = await http.post('/v1_0/authorizations', { mobile, code })
    console.log(res)
    // 保存到 redux
    dispatch({ type: 'user/saveAuth', payload: res.data })
    // 保存本地
    setTokenInfo(res.data)
  }

export const getUserInfo = () => async (dispatch: AppDispatch) => {
  const res = await http.get('/v1_0/user')
  console.log(res)
  // 保存到 redux
  dispatch({ type: 'user/saveUser', payload: res.data })
}

export const getUserProfile = () => async (dispatch: AppDispatch) => {
  const res = await http.get('/v1_0/user/profile')
  console.log(res)
  // 保存到 redux
  dispatch({ type: 'user/saveProfile', payload: res.data })
}

export const editUserPhoto =
  (fd: FormData) => async (dispatch: AppDispatch) => {
    const res = await http.patch('/v1_0/user/photo', fd)
    console.log(res)
    // 保存到 redux
    dispatch({ type: 'user/updateProfile', payload: res.data })
  }

export const editUserProfile =
  (data: Partial<Profile>) => async (dispatch: AppDispatch) => {
    const res = await http.patch('/v1_0/user/profile', data)
    console.log(res)
    dispatch({ type: 'user/updateProfile', payload: data })
  }

// 清空用户数据
export const clearAuth = (): UserAction => ({ type: 'user/clearAuth' })
